import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import router from 'umi/router';

import { Form } from '@ant-design/compatible';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import PageHeader from '@/components/PageHeader';

import {
  Card,
  Row,
  Col,
  Button,
  ConfigProvider,
  Table,
  Descriptions,
  message,
  InputNumber,
  Popconfirm,
} from 'antd';

import WhiteList from './components/WhiteList';

import '@ant-design/compatible/assets/index.css';

const cellDesc = {
  10901: '大箱',
  10902: '中箱',
  10903: '小箱',
  10904: '超小箱',
  10905: '大(宽)箱',
  10906: '中(宽)箱',
  10907: '小(宽)箱',
  10908: '超小(宽)箱',
  10909: '文件箱',
  10910: '文件(宽)箱',
  10911: '超大箱',
  10912: '超大(宽)箱',
};

interface DeliveryWhiteListProps extends FormComponentProps {
  dispatch: Dispatch;
  loading: any;
  cellList: any;
  cellInfo: any;
  dataInfo: any;
  location: { query: any };
}

interface DeliveryWhiteListState {
  pageIndex: number;
  pageSize: number;
  addVisible: boolean;
}

@connect(
  ({
    deliveryWhiteList: { cellList, cellInfo, dataInfo },
    loading,
  }: any) => ({
    cellList,
    cellInfo,
    dataInfo,
    loading: loading.effects['deliveryWhiteList/fetchWhiteCourier'],
  }),
)
class DeliveryWhiteList extends Component<DeliveryWhiteListProps, DeliveryWhiteListState> {
  columns: any = [
    { title: '快递员姓名', dataIndex: 'name' },
    { title: '快递员手机号', dataIndex: 'phone' },
    { title: '添加时间', dataIndex: 'createTime' },
    { title: '操作人', dataIndex: 'createUserName' },
    {
      title: '操作',
      dataIndex: 'id',
      render: (id: number) => (
        <Popconfirm
          title="确定要删除当前快递员吗？"
          okText="确定"
          cancelText="取消"
          onConfirm={() => this.handleDelete(id)}
        >
          <Button type="link">
            删除
          </Button>
        </Popconfirm>
      ),
    },
  ];

  state: DeliveryWhiteListState = {
    pageIndex: 1,
    pageSize: 20,
    addVisible: false,
  };

  componentDidMount() {
    const { location: { query } } = this.props;

    if (query && query.id) {
      this.fetchAction('fetchCellList', { cabinetId: query.id });
      this.fetchAction('fetchCellConf', { cabinetId: query.id });
      this.fetchAction('fetchWhiteCourier', { cabinetId: query.id });
    } else message.error('当前配置信息不存在!');
  }

  handleChangeAdd = (addVisible: boolean = true) => {
    this.setState({ addVisible }, () => {
      if (addVisible) {
        const { location: { query } } = this.props;
        const params = {
          cabinetId: query.id,
          pageIndex: 1,
          pageSize: 5,
        };

        this.fetchAction('fetchOtherCourier', params);
      }
    });
  };

  handleDelete = (id: number) => {
    const {
      pageIndex,
      pageSize,
    } = this.state;

    const { location: { query } } = this.props;

    const params = {
      id,
      pageIndex,
      pageSize,
      cabinetId: query.id,
    };

    this.fetchAction('deleteCourier', params);
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { location: { query } } = this.props;
    const params = {
      cabinetId: query.id,
      pageIndex,
      pageSize,
    };

    this.setState({
      pageIndex,
      pageSize,
    }, () => this.fetchAction('fetch', params));
  };

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch } = this.props;
    dispatch({
      type: `deliveryWhiteList/${typeName}`,
      payload,
    });
  };

  handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    const {
      form: { validateFieldsAndScroll },
      cellInfo,
    } = this.props;

    validateFieldsAndScroll((errors, values) => {
      if (!errors) {
        const confInfo = Object.keys(values).reduce((origin: any, cellId: any) => {
          let conf = cellInfo.find((cell: any) => cell.cellType === Number(cellId))?.id || '';
          conf += `-${cellId}-${values[cellId]}`;
          origin.push(conf);

          return origin;
        }, []).join(',');

        const { location: { query } } = this.props;
        this.fetchAction('saveCellConf', { cabinetId: query.id, confInfo });
      }
    });
  };

  render() {
    const {
      addVisible,
      pageIndex,
      pageSize,
    } = this.state;

    const {
      form: { getFieldDecorator },
      cellList,
      cellInfo,
      dataInfo,
      location: { query },
      loading,
    } = this.props;

    const dataSource = dataInfo ? dataInfo.list : [];
    const pagination: object = {
      total: dataInfo ? dataInfo.count : 0,
      current: pageIndex,
      pageSize,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showTotal: () => `共${dataInfo.count || 0}条数据`,
      onChange: this.onSelectChange,
      onShowSizeChange: this.onSelectChange,
    };

    const props = {
      addVisible,
      cabinetId: query.id,
      changeAdd: this.handleChangeAdd.bind(this),
    };

    return (
      <Fragment>
        <PageHeader />
        <Row
          gutter={{ md: 8, xl: 24, lg: 48 }}
          style={{ marginLeft: 0, marginRight: 0, marginTop: 12 }}
        >
          <Col md={8} sm={24}>
            <Card title="基本信息" bordered={false}>
              <Descriptions column={1}>
                <Descriptions.Item label="柜体名称">{query.name}</Descriptions.Item>
                <Descriptions.Item label="柜体编号">{query.code}</Descriptions.Item>
                <Descriptions.Item label="柜体状态">{query.statusName}</Descriptions.Item>
              </Descriptions>
            </Card>

            <Card
              title={
                <span>格口配置
                  <span style={{ fontSize: 14 }}>
                    （只用于白名单外快递员）
                  </span>
                </span>
              }
              bordered={false}
              style={{ marginTop: 12, fontWeight: 400 }}
            >
              <Form hideRequiredMark className="tableListForm" onSubmit={this.handleSubmit}>
                {
                  Object.keys(cellList)
                    .filter((cellId: string) => cellList[cellId].count > 0)
                    .map((cellId: string) => (
                      <Row key={cellId} gutter={{ md: 24, xl: 24, lg: 48 }}>
                        <Col>
                          <Form.Item
                            colon={false}
                            label={
                              <div style={{ width: 100 }}>
                                {cellDesc[cellId]}(<span style={{ color: '#ff4d4f' }}>{cellList[cellId].count}</span>):
                              </div>
                            }
                          >
                            <div style={{ display: 'flex' }}>
                              {getFieldDecorator(cellId, {
                                initialValue: cellInfo
                                  .find((cell: any) => cell.cellType === Number(cellId))?.outCellCount || 0,
                                rules: [
                                  { required: true, message: `${cellDesc[cellId]}次数不能为空` },
                                  { pattern: /^\d+$/, message: '只能输入整数' },
                                  { type: 'number', max: cellList[cellId].count, message: `${cellDesc[cellId]}最大配置为${cellList[cellId].count}` },
                                ],
                              })(
                                <InputNumber
                                  min={0}
                                  style={{ width: '100%' }}
                                />,
                              )}
                              <span style={{ marginLeft: 8 }}>次</span>
                            </div>
                          </Form.Item>
                        </Col>
                      </Row>
                    ))
                }

                <div style={{
                  display: 'flex',
                  margin: 10,
                  fontSize: 12,
                  color: '#ff4d4f',
                }}
                >
                  <div style={{ width: 48 }}>说明</div>
                  <div>
                    <div>1、每类格口类型最大投递次数不能大于对应格口最大数量；</div>
                    <div>2、每类格口类型最小投递次数可配置0，配置0后未添加至表中的快递员对应格口类型可用投递次数为0；</div>
                    <div>3、”（）“内的数字代表该类型格口的总数；</div>
                    <div>4、更新格口配置和白名单列表数据保存后实时生效。</div>
                  </div>
                </div>

                <Row gutter={{ md: 8, xl: 24, lg: 48 }} style={{ marginTop: 12 }}>
                  <Col>
                    <Button type="primary" htmlType="submit">
                      保存
                    </Button>
                    <Button type="primary" ghost className="marginL16" onClick={() => router.goBack()}>
                      取消
                    </Button>
                  </Col>
                </Row>
              </Form>
            </Card>
          </Col>
          <Col md={16} sm={24}>
            <Card bordered={false}>
              <ConfigProvider autoInsertSpaceInButton={false}>
                <Button
                  type="primary"
                  size="small"
                  className="addButton marginB12"
                  onClick={() => this.handleChangeAdd()}
                >
                  添加白名单快递员
                </Button>
              </ConfigProvider>
              <Table
                rowKey="id"
                className="statementTable"
                columns={this.columns}
                dataSource={dataSource}
                pagination={pagination}
                loading={loading}
              />
            </Card>
          </Col>
        </Row>

        <WhiteList {...props} />
      </Fragment>
    );
  }
}

export default Form.create<DeliveryWhiteListProps>()(DeliveryWhiteList);
